package com.cndw.kungfu.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.comm.CommInspection;
import com.cndw.kungfu.comm.PositionInspection;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsChat;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Monster;
import com.cndw.kungfu.domain.MonsterDeploy;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Scene;
import com.cndw.kungfu.domain.Undercity;
import com.cndw.kungfu.event.once.PlayerStateTask;
import com.cndw.kungfu.event.once.PlayerWallTask;
import com.cndw.kungfu.ext.ImageCode;
import com.cndw.kungfu.ext.LangUtil;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.MD5;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.StringProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.activity.ModeSceneWall;
import com.cndw.kungfu.model.battle.Battle;
import com.cndw.kungfu.model.battle.FailGoods;
import com.cndw.kungfu.model.battle.FighterMonster;
import com.cndw.kungfu.model.battle.Team;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.sys.ChatMain;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.model.undercity.PlayerUndercity;
import com.cndw.kungfu.model.undercity.UndercityManager;
import com.cndw.kungfu.vo.PlayerReceiveVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 战斗管理
 * 
 * @author fantadust
 * 
 */
@Controller
public class BattleController {
	@Autowired
	private UndercityManager undercityManager;

	/**
	 * 进入怪物打斗场景
	 * 
	 * @param session
	 * @param monsterDeployId
	 * @return
	 */
	public ResponseMessage enterBattle(Session session, int monsterDeployId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		MonsterDeploy monsterDeploy = Context.getUndercityServer().getDeployById(monsterDeployId);
		if (monsterDeploy == null) {
			return null;
		}
		if (PositionInspection.checkMonster(player, monsterDeploy) == false) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"));
		}
		final int currentTime = TimeProcesser.getUnixTime();

		Scene scene = Context.getSceneServer().getSceneById(monsterDeploy.getSceneId());
		PlayerUndercity playerUndercity = null;
		if (scene.isCityUndercity()) {
			playerUndercity = Context.getUndercityServer().getPlayerUndercity(player.getPlayerId());
			if (playerUndercity == null || playerUndercity.isPassDeploy(monsterDeployId)) {
				return null;
			} else if (playerUndercity.isOpenScene(monsterDeploy.getSceneId()) == false) {
				return null;
			}
			// 通天图、神兵阵超时，无法打怪
			if (((playerUndercity.getUndercity().getType() == Undercity.typeSoldierCheckpoint || playerUndercity.getUndercity().getType() == Undercity.typePicCheckpoint)
					&& scene.getLiftTime() > 0 && currentTime - playerUndercity.getEnterTime() > scene.getLiftTime())
					|| playerUndercity.isDead()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.enter.forceout"));
			}
		} else if (scene.isCityWall()) {
			if (!Context.getSceneServer().checkIsWallKillTime()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.enter.end")); // 即将活动结束，不能战斗
			}

			if (BlankUtils.isBlank(player.getTeam())) {
				if (!ModeSceneWall.getPlayer(player.getPlayerId()).checkPlayerActiveStatus()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.enter.myexile"));
				}
			} else {
				for (Player p : player.getTeam().getBattlePlayers()) {
					if (ModeSceneWall.containsPlayer(p.getPlayerId()) && !ModeSceneWall.getPlayer(p.getPlayerId()).checkPlayerActiveStatus()) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.enter.exile", p.getPlayerName()));
					}
				}
			}
		}
		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;

		if (player.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.cooling"));
		}
		if (player.stateContains(Constants.playerState1024_aiUndercity)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("undercity.ai.err"));
		}
		if (!scene.isCityUndercity() && ConstantsConfig.isInspectComm(Constants.inspectBattle)) {
			if (player.getDataInfo().getEveryDay().getPveBug() >= ConstantsModel.wgBattleErrNum) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.wg"));
			}
			if (player.stateContains(Constants.playerState512_battleAuto)) {
				if (currentTime - player.getDataInfo().getLastPve() < 4) {
					player.getDataInfo().getEveryDay().alterPveBug(10);
				}
			}
		}
		if (monsterDeploy.getRefreshApp() > 0) {// 世界boss击杀接口错开
			return null;
		}

		int battleId = player.getDataInfo().getBattleId();
		if (battleId > 0) {
			Battle battle = Context.getDataServer().getBattleMap().get(battleId);
			if (battle != null) {
				if (battle.getEndTime() > currentTime) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.cooling"));
				}
				if (battle.isAllReceive() || battle.getAllPlayers().size() == 1) {
					battle.clear();
				}
			}
		}
		int addMonster = 0;
		Team sourceTeam = player.getTeam();
		if (sourceTeam != null) {
			// 队员不在队长旁边不能开怪
			if (sourceTeam.isMaster(player.getPlayerId()) == false && player.getSceneId() != sourceTeam.getMaster().getSceneId()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.team.errenter"));
			}
			if (monsterDeploy.getDefaultMonster() != null && monsterDeploy.getDefaultMonster().boss == 0 && scene.isCityField()
					&& sourceTeam.getBattleMembers().size() > 1) {
				addMonster = NumberProcesser.mtRand(5 - monsterDeploy.getMonsterIdsList().size());
			}
		}
		List<FighterMonster> monstersList = undercityManager.initMonstersByDeploy(monsterDeployId, addMonster);
		if (monstersList == null) {
			return null;
		}
		int battleNum = monstersList.size();
		try {
			if (sourceTeam != null && sourceTeam.getId() > 0) {
				sourceTeam.getMainLock().lock();// 锁定
				for (Player memberPlayer : sourceTeam.getBattlePlayers()) {
					if (memberPlayer.stateContains(Constants.playerState1_battle)) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.team.noexit", memberPlayer.getPlayerName()));
					}
				}
			}
			Battle battle;
			if (playerUndercity != null && playerUndercity.getPowerCoef() != 0) {
				battle = new Battle(player.getLikedFighter(playerUndercity.getPowerCoef()), monstersList, monsterDeploy.getDefaultMonsterId());
			} else {
				battle = new Battle(player, monstersList, monsterDeploy.getDefaultMonsterId());
			}
			battle.config(0, scene.getType(), 0);
			if (playerUndercity!= null && playerUndercity.isRateDouble()) {
				battle.setRateCoef(true);
			}
			battle.execBattle(Constants.battle_pve);
			battle.deployReport(monsterDeployId);
			battle.broadcast();

			if (scene.isCityUndercity()) {
				if (battle.getBattleReport().getWiner() == 1) {
					playerUndercity.passDeploy(monsterDeployId);
					playerUndercity.checkPassScene(monsterDeploy.getSceneId(), battle.getBattleReport().getEndTime());
				} else {
					playerUndercity.checkFailed();
				}
			}
			if (sourceTeam != null && sourceTeam.getId() > 0) {
				sourceTeam.setBattleId(battle.getId());
				for (Player memberPlayer : battle.getAllPlayers()) {
					memberPlayer.stateAdd(Constants.playerState1_battle);
					Context.getPlayerServer().broadcaseState(memberPlayer);
					memberPlayer.getDataInfo().setBattleId(battle.getId());
					if (ConstantsConfig.isInspectComm(Constants.inspectBattle)) {
						memberPlayer.getDataInfo().setLastPve(battle.getEndTime());
					}
					if (scene.isCityField()) {
						memberPlayer.getDataInfo().getEveryDay().alterBattleNum(battleNum);
					}
					QQDC.getInstance().logClick(memberPlayer, LogFieldType.battle);
				}

			} else {
				player.stateAdd(Constants.playerState1_battle);
				Context.getPlayerServer().broadcaseState(player);
				player.getDataInfo().setBattleId(battle.getId());
				if (ConstantsConfig.isInspectComm(Constants.inspectBattle)) {
					player.getDataInfo().setLastPve(battle.getEndTime());
				}
				if (scene.isCityField()) {
					player.getDataInfo().getEveryDay().alterBattleNum(battleNum);
				}
				QQDC.getInstance().logClick(player, LogFieldType.battle);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sourceTeam != null && sourceTeam.getId() > 0) {
				sourceTeam.getMainLock().unlock();// 解锁
			}
		}

		return null;
	}

	/**
	 * 领取物品
	 * 
	 * @param session
	 * @param indexIds
	 * @return
	 */
	public ResponseMessage receiveTrophy(Session session, String indexIds) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int battleId = player.getDataInfo().getBattleId();
		if (battleId <= 0) {
			return null;
		}

		Battle battle = Context.getDataServer().getBattleMap().get(battleId);

		if (battle == null) {
			return null;
		}
		int IntervalSconds = TimeProcesser.getUnixTime() - battle.getBattleReport().getEndTime();
		if (ConstantsConfig.isInspectComm(Constants.inspectBattle) && player.getLevel() >= 45) {
			if (IntervalSconds < 0) {
				player.getDataInfo().getEveryDay().alterPveBug(10);
			} else if (IntervalSconds < 1) {
				player.getDataInfo().getEveryDay().alterPveBug(2);
			}
		}
		if (IntervalSconds < 0) {
			return null;
		}
		if (battle.isReceive(player.getPlayerId())) {
			return null;
		}
		List<Integer> ids = StringProcesser.toIntList(indexIds);
		Map<Integer, FailGoods> failGoodsMap = battle.getFailGoodsMap();
		List<FailGoods> owerFailGoods = new ArrayList<FailGoods>();
		int needBlack = 0;
		if (failGoodsMap != null && ids != null) {
			for (Integer indexId : ids) {
				FailGoods e = failGoodsMap.get(indexId);
				if (e != null && e.getPlayerId() == player.getPlayerId() && e.getGoodsId() > 0) {
					owerFailGoods.add(e);
					GoodsMode goodsMode = Context.getGoodsServer().getModeById(e.getGoodsId());
					if (!goodsMode.isTaskItem()) {
						needBlack++;
					}
				}
			}
		}

		if (needBlack > 0) {
			PlayerBoxs playerBoxs = player.getPlayerBoxs();
			if (!playerBoxs.checkBlack(needBlack)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", needBlack));
			}
		}
		battle.signReceive(player.getPlayerId());

		GoodsMode lastGoods = null;
		List<String> dropGoods = new LinkedList<String>();
		for (FailGoods e : owerFailGoods) {
			failGoodsMap.remove(e.getIndexId());// 清理掉落
			Context.getGoodsServer().giveGoodsBing(player.getPlayerId(), e.getGoodsId(), 1, e.getBind());
			lastGoods = Context.getGoodsServer().getModeById(e.getGoodsId());
			dropGoods.add(lastGoods.getName());

			if (lastGoods.getColor() >= 3 && lastGoods.isEquiq()) {
				Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
				ChatMain.hearsayMessage(
						LanguageLib.get("chat.board.equip", LangUtil.makeNameLink(player), scene.getName(), lastGoods.getName(),
								LangUtil.getColor(lastGoods.getColor())), ConstantsChat.cwGot);
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();

		PlayerReceiveVO receiveVO = new PlayerReceiveVO();

		player.alterExp(battle.getExp());
		receiveVO.put(PlayerReceiveVO.RECEIVE_EXP, battle.getExp());
		if (battle.getAsset() > 0) {
			player.alterAsset(battle.getAsset());
			receiveVO.put(PlayerReceiveVO.RECEIVE_ASSET, battle.getAsset());
		}
		player.getDataInfo().setBattleId(0);
		// 战斗对象从列表删除
		if (battle.isAllReceive()) {
			battle.clear();
		}

		player.stateRemove(Constants.playerState1_battle);
		Context.getPlayerServer().broadcaseState(player);
		player.commitSync();// 提交同步

		map.put("receiveVO", receiveVO);
		map.put("player", player.toPlayerVO());
		if (ConstantsConfig.isInspectComm(Constants.inspectBattle)) {
			if (player.getDataInfo().getEveryDay().getPveBug() >= ConstantsModel.wgBattleErrNum) {
				map.put("captcha", true);// 标志需要输入验证码
			}
		}
		map.put("bn", player.getDataInfo().getEveryDay().getBattleNum());

		boolean win = battle.getWiner() == 1;

		// 添加“战斗-打怪”日志
		LogServer.recordLog(player, ConstantsLog.battle, 40001, battle.getTargetMasterName(), win, battle.getExp(), battle.getAsset(), dropGoods);
		if (battle.getDefaultMonsterId() > 0) {
			Monster monster = Context.getUndercityServer().getMonster(battle.getDefaultMonsterId());
			if (win && (battle.getDefaultMonsterId() == 107) && player.getLevel() <= 15) {
				// ChatMain.systemMessage(LanguageLib.get("chat.board.kill",
				// player.getPlayerName(), monster.getName()));
			} else if (monster.getBoss() == 3 && lastGoods != null) {
				ChatMain.systemMessage(LanguageLib.get("chat.board.killworldboss", LangUtil.makeNameLink(player), monster.getName(), lastGoods.getName(),
						LangUtil.getColor(lastGoods.getColor())));
			} else if (win) {
				PlayerUndercity playerUndercity = Context.getUndercityServer().getPlayerUndercity(player.getPlayerId());
				if (playerUndercity != null && playerUndercity.isPassThroug()) {
					if (playerUndercity.getUndercity().getType() == Undercity.typeDrama && playerUndercity.getUndercityId() >= 1001
							&& playerUndercity.getUndercityId() <= 1099) {
						int tmpId = playerUndercity.getUndercityId() - 1000;
						int key = tmpId / 9;
						String langKey = "chat.dream.k";
						if (tmpId % 9 == 0) {
							langKey = langKey + (key) + "1";
							ChatMain.systemMessage(LanguageLib.get(langKey, player.getPlayerName(), monster != null ? monster.getName() : playerUndercity
									.getUndercity().getName()));
						} else {
							// langKey = langKey + (key + 1) + "0";
						}

						Context.getTaskServer().autoRaidioTask(player.getPlayerId(), 1);
					} else {
						if (monster.getBoss() == 2) {
							// ChatMain.systemMessage(LanguageLib.get("chat.board.killboss"
							// + NumberProcesser.mtRand(3),
							// player.getPlayerName(), monster.getName(),
							// playerUndercity.getUndercity().getName()));
						}
					}

				}
			}

		}

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 刺杀
	 * 
	 * @param session
	 * @param playerId
	 * @return
	 */
	public ResponseMessage slaughter(Session session, long targetId) {
		final Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		final Player target = Context.getPlayerServer().getByPlayerId(targetId);
		if (target == null || player.getSceneId() != target.getSceneId()) {
			return null;
		}

		Scene scene = Context.getSceneServer().getSceneById(target.getSceneId());
		if (scene.getType() != Constants.CITY_WALL) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.erscene"));
		}

		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;

		if (player.getDataInfo().getLastSlaughter() + 5 >= TimeProcesser.getUnixTime()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.soucecooling"));
		} else if (target.getDataInfo().getLastSlaughter() + 5 >= TimeProcesser.getUnixTime()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.targetcooling"));
		}

		// 塞外非活动玩家不能刺杀，也不能被刺杀
		if (scene.isCityWall()) {
			if (!Context.getSceneServer().checkIsWallKillTime()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.end")); // 即将活动结束，不能刺杀
			}

			if (player.getTeamId() > 0 && player.getTeamId() == target.getTeamId()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.team")); // 同组的人不可以刺杀
			}

			if (BlankUtils.isBlank(player.getTeam())) {
				if (player.stateContains(noKill)) {
					return null;
				}
				if (!ModeSceneWall.getPlayer(player.getPlayerId()).checkPlayerActiveStatus()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.myexile"));
				}
			} else {
				for (Player p : player.getTeam().getBattlePlayers()) {
					if (p.stateContains(noKill)) {
						return null;
					}
					if (ModeSceneWall.containsPlayer(p.getPlayerId()) && !ModeSceneWall.getPlayer(p.getPlayerId()).checkPlayerActiveStatus()) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.exile", p.getPlayerName()));
					}
				}
			}

			if (BlankUtils.isBlank(target.getTeam())) {
				if (target.stateContains(noKill)) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.errinbattle"));
				}
				if (!ModeSceneWall.getPlayer(target.getPlayerId()).checkPlayerActiveStatus()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.texile"));
				}
			} else {
				for (Player p : target.getTeam().getBattlePlayers()) {
					if (p.stateContains(noKill)) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.errinbattle"));
					}
					if (ModeSceneWall.containsPlayer(p.getPlayerId()) && !ModeSceneWall.getPlayer(p.getPlayerId()).checkPlayerActiveStatus()) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.slaughter.texile"));
					}
				}
			}
		}

		Battle battle = new Battle(player, target);
		battle.execBattle(Constants.battle_slaughter);
		battle.broadcast();
		// 战斗对象从列表删除
		battle.clear();

		for (Player battlePlayer : battle.getAllPlayers()) {
			battlePlayer.stateAdd(Constants.playerState4_slaughter);
			battlePlayer.getDataInfo().setLastSlaughter(battle.getBattleReport().getEndTime());
			Context.getPlayerServer().broadcaseState(battlePlayer);
		}

		new PlayerWallTask(Constants.playerState4_slaughter, battle.getCostTime(), battle.getWiner(), scene, player, target);

		// 添加“战斗-刺杀”日志
		LogServer.recordLog(player, ConstantsLog.battle, 40003, target.getPlayerName(), target.getPlayerId(), battle.getWiner() == 1 ? true : false);
		QQDC.getInstance().logClick(player, LogFieldType.battleSlaughter);
		return null;
	}

	/**
	 * 请求切磋
	 * 
	 * @param session
	 * @param targetId
	 * @return
	 */
	public ResponseMessage learn(Session session, long targetId) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Player target = Context.getPlayerServer().getByPlayerId(targetId);
		if (target == null) {
			return null;
		}

		if (!PositionInspection.checkPlayer(player, target)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"));
		}
		if (player.getTeamId() > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.team"));
		} else if (target.getTeamId() > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.oteam"));
		}

		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;
		if (player.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.errinbattle"));
		} else if (target.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.targertbattle"));
		} else if (target.stateContains(Constants.playerState256_dart)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.targertdart"));
		} else if (player.stateContains(Constants.playerState256_dart)) {
			return null;
		}

		Scene scene = Context.getSceneServer().getSceneById(target.getSceneId());
		if (scene.isCityWall() || scene.isCityUndercity() || scene.isCityUnionWar()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.errscene"));
		}
		Team sourceTeam = player.getTeam();

		if (sourceTeam != null && sourceTeam.isMaster(session.getUid()) == false) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.control.notmaster"));
		}
		Team targeTeam = target.getTeam();
		if (targeTeam != null) {
			targetId = targeTeam.getMaster().getUniqueId();
			Player masterPlayer = Context.getPlayerServer().getByPlayerId(targetId);
			if (masterPlayer.getSceneId() != target.getSceneId()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.team.errscenee"));
			}
		}

		player.getDataInfo().setLearnTargetId(targetId);// 记录申请的玩家id

		String title = LanguageLib.get("battle.learn.title", player.getPlayerName());

		Object parameters = new Object[] { session.getUid() };
		Context.getTcpServer().broadcastConfirm(title, "BattleController", "replyLearn", 3, parameters, targetId);

		return null;
	}

	/**
	 * 应答切磋
	 * 
	 * @param session
	 * @param agree
	 * @param targetId
	 * @return
	 */
	public ResponseMessage replyLearn(Session session, long targetId, boolean agree) {
		final Player player = Context.getPlayerServer().getByPlayerId(targetId);
		final Player target = Context.getPlayerServer().getByPlayerId(session.getUid());

		if (player.getDataInfo().getLearnTargetId() != session.getUid()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.errtime"));
		}

		player.getDataInfo().setLearnTargetId(0);
		if (agree == false) {
			String title = LanguageLib.get("battle.learn.titlerefusal", target.getPlayerName());
			ResponseMessage message = ResponseMessage.ticpErrMsg(title);
			Context.getTcpServer().broadcastResMsg(message, targetId);
			return null;
		}

		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;
		if (player.stateContains(noKill)) {
			return null;
		} else if (target.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.targertbattle"));
		}

		Scene scene = Context.getSceneServer().getSceneById(target.getSceneId());
		if (scene.isCityWall() || scene.isCityUndercity() || scene.isCityUnionWar()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.errscene"));
		}

		if (player.getTeamId() > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.team"));
		} else if (target.getTeamId() > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.learn.oteam"));
		}

		player.stateAdd(Constants.playerState2_learn);
		target.stateAdd(Constants.playerState2_learn);

		Battle battle = new Battle(target, player);
		battle.execBattle(Constants.battle_learn);
		battle.broadcast();
		// 战斗对象从列表删除
		battle.clear();
		// 广播状态
		for (Player battlePlayer : battle.getAllPlayers()) {
			battlePlayer.stateAdd(Constants.playerState2_learn);
			Context.getPlayerServer().broadcaseState(battlePlayer);
		}
		String lang = "chat.learn.suc" + NumberProcesser.mtRand(2);
		String message = LanguageLib.get(lang, target.getPlayerName(), player.getPlayerName(),
				battle.getWiner() == 1 ? target.getPlayerName() : player.getPlayerName(), scene.getName());

		ChatMain.systemMessageDelay(message, battle.getCostTime() + 5);

		new PlayerStateTask(Constants.playerState2_learn, battle.getCostTime(), battle.getAllPlayers());

		// 添加“战斗-挑战”日志
		LogServer.recordLog(player, ConstantsLog.battle, 40002, target.getPlayerName(), target.getPlayerId(), battle.getWiner() == 1 ? true : false);
		QQDC.getInstance().logClick(player, LogFieldType.battleLearn);
		QQDC.getInstance().logClick(target, LogFieldType.battleLearn);
		return null;
	}

	public ResponseMessage captchaGet(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		Object[] apimsg = null;
		int numTest = ConstantsConfig.isInspectComm(Constants.inspectQQCode) ? 2 : 0;
		for (int i = 0; i < numTest; i++) {
			apimsg = CommInspection.captchaGet(player);
			if (apimsg == null) {
				LogUtil.getMain().debug("null");
				continue;
			}
			if (apimsg[1].toString().indexOf("image") >= 0) {
				String disposition = apimsg[2].toString();
				int lengstart = disposition.indexOf("filename=");
				String filename = disposition.substring(lengstart + 9);
				filename = filename.split(";")[0].trim();
				return ResponseMessage.getSuccMessage(new Object[] { filename, apimsg[0] });
			} else {
				String tmpMsg = new String((byte[]) apimsg[0]);
				LogUtil.getMain().debug(tmpMsg);
			}
		}
		ImageCode imageCode = new ImageCode(130, 50, 4);
		imageCode.createCheckCode();
		String filename = imageCode.getCheckCodeStr();
		filename = filename.toLowerCase();
		StringBuilder sb = new StringBuilder();
		int currentTime = TimeProcesser.getUnixTime();
		sb.append("dv,linzi,").append(currentTime).append(",");
		sb.append(MD5.compile16(filename + ".fantadust." + session.getUid() + currentTime));
		filename = sb.toString();
		return ResponseMessage.getSuccMessage(new Object[] { filename, imageCode.createBytes() });
	}

	public ResponseMessage captchaVerify(Session session, String verifysig, String verifycode) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (verifysig == null) {
			return null;
		}
		boolean suc = false;
		if (verifysig.indexOf("dv,linzi,") >= 0) {
			String[] singarr = verifysig.toString().split(",");
			if (Integer.valueOf(singarr[2]) <= TimeProcesser.getUnixTime() - 120) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.wgtime"));
			}
			StringBuilder sb = new StringBuilder();
			sb.append(verifycode.toLowerCase()).append(".fantadust.").append(session.getUid()).append(singarr[2]);
			if (MD5.compile16(sb.toString()).equals(singarr[3])) {
				suc = true;
			}
		} else {
			suc = CommInspection.captchaVerify(player, verifysig, verifycode);
		}
		if (suc) {
			player.getDataInfo().getEveryDay().setPveBug(0);
		}

		return ResponseMessage.getSuccMessage(suc);
	}

}
